BASIC PYTHON FOR RESEARCHERS

by Megat Harun Al Rashid bin Megat Ahmad
last updated: April 14, 2016


1. Mathematical Operations

Simple mathematical operations are part of the native Python features but advanced mathematical tools can be accessed by importing the **math** library.


In [1]:
from math import *

The syntax above when executed allows the usage of mathematical functions available in the **math** library. The '*' means everything i.e. all functions in the **math** library are imported and can be used. It is also possible to import a specific function and rename it but this will be explored in the forthcoming tutorials.

Now let us do some simple mathematical operations:


1.1 Addition and Substraction


In [2]:
12+7


Out[2]:
19

In [3]:
23 + 67 - 34


Out[3]:
56

Trailing white space is ignored by Python. Operation on floating points is automatic but can also be declared using the **float()** function:


In [4]:
12.34 + 8


Out[4]:
20.34

In [5]:
float(13) - 7


Out[5]:
6.0

1.2 Multiplication and Division


In [6]:
12 * 38


Out[6]:
456

In [7]:
9 / 3


Out[7]:
3

In [8]:
15/6


Out[8]:
2

Division between integers will give a truncated integer value (rather than the number being rounded up). It is good practice to use floating point number instead, by declaring one of the integer with decimal point.


In [9]:
15.0/6


Out[9]:
2.5

1.3 Exponent and Root

Exponent can be declared by using 'e' or 'E' letters with no trailing space:


In [10]:
3E12


Out[10]:
3000000000000.0

In [11]:
7.9e-12 * 6


Out[11]:
4.74e-11

Power (and root) can be declared by using the '**' character. For instance, the operation for $2^3$ is:


In [12]:
2**3


Out[12]:
8

and for $\sqrt[3]{8}$ (in which it should produces the value $2$).


In [13]:
8**1.0/3


Out[13]:
2.6666666666666665

but here it did not produce the value of 2 because the term $8^{1.0}$ is evaluated first before being divided by the number $3$. Herein users need to know that Python follows the usual order of operations in mathematical expressions. The standard order of operations is expressed in the following enumeration:

  1. Exponent and Root.
  2. Multiplication and Division.
  3. Addition and Substraction.

Lower order can be prioritize by using parenthesis.

To get the correct value for $8^{\frac{1}{3}}$, the $1.0/3$ operation need to be parenthesized which means that it will be evaluated first instead of the operation $8^{1.0}$.


In [14]:
8**(1.0/3)


Out[14]:
2.0

This floating value can be change into an integer by declaring it as integer using the **int()** function:


In [15]:
int(8**(1.0/3))


Out[15]:
2

Power and root operations can also be performed by using their respective built-in functions:


In [16]:
sqrt(9)


Out[16]:
3.0

which is the operation for $\sqrt{9}$ whereas...


In [17]:
pow(2,3)


Out[17]:
8.0

...is the operation for $2^3$. Users can also used **pow()** function to perform root operation.


In [18]:
pow(9,(1.0/2))


Out[18]:
3.0

In [19]:
pow(8.2,0.43)


Out[19]:
2.4713824398960362

The **log($x$)** and **log10($x$)** functions respectively return natural and base 10 logarithmic for **$x$** value.


In [20]:
log(100)


Out[20]:
4.605170185988092

In [21]:
log10(1000)


Out[21]:
3.0

The function **log($x$,$y$)** returns base $y$ for $x$ value. Exponential value can directly be used using the 'e' letter.


In [22]:
log(1000,8)


Out[22]:
3.3219280948873626

In [23]:
e


Out[23]:
2.718281828459045

In [24]:
log(e)


Out[24]:
1.0

1.4 Trigonometric functions

Python only accepts radians value for trigonometric operations. For instance, an angle with a value of $60^o$ needs to be converted to radians before trigonometric operation. This include the usage of $\pi$ which can directly be used using the 'pi' term.


In [25]:
pi


Out[25]:
3.141592653589793

In [26]:
sin(60*pi/180)


Out[26]:
0.8660254037844386

Floating point arithmatic is not exact because decimal fraction cannot be represented exactly as binary (base 2) fraction in the computer hardware logical operation as evidenced by the two instances below (where both operations should give exact value of $0.5$)


In [27]:
sin(30*pi/180)


Out[27]:
0.49999999999999994

In [28]:
cos(60*pi/180)


Out[28]:
0.5000000000000001

Apart from operating with $\pi$ users can also used the **radians($x$)** function which converts $x$ degrees into radians (and there is also **degrees($x$)** function that convert radians into degrees).


In [29]:
sin(radians(60))


Out[29]:
0.8660254037844386

In [30]:
degrees(0.5*pi)


Out[30]:
90.0

In [31]:
sin(radians(30))**2 + cos(radians(30))**2


Out[31]:
1.0

Example 1.1: What is the value of $\theta$ in degree if y = 1 and x = 1.732 in the Figure 1 below

                                        Figure  1

$Answer$:


In [32]:
atan2(1,1.732)*180/pi


Out[32]:
30.000727780827372

Arc tangent value can be obtained using the **atan2($y$,$x$)** function that give the angle $\theta$ value in radian. Alternatively, users can calculate the value of $y$/$x$ first and then use it as the $x$ argument for **atan($x$)** function.


In [33]:
atan(1/1.732)*180/pi


Out[33]:
30.000727780827372

Example 1.2: From the values given in Example 1.1 what is the hypotenuse value of the triangle and calculate $\theta$ using this hypotenuse value and the given $x$ value.

$Answer$:


In [34]:
hypot(1.732,1)


Out[34]:
1.9999559995159892

In [35]:
degrees(acos(1.732/2))


Out[35]:
30.002910931188026

Further mathematical functions on **math** library can be found in https://docs.python.org/2/library/math.html


1.5 Variables

A numerical value can be assigned to a variable by using the '=' operation. For instance:


In [36]:
x = 34.5

which means that $x$ has been assigned a value of 34.5. In Python, variable type is specified during the assignment of the variable and need not be declared beforehand e.g. if an integer is assigned to a variable, then the variable is of integer type. Variables can be operated much like numerics.


In [37]:
y = 23.9
z = 12
add = y + z - 5.7
add


Out[37]:
30.2

Variable names must consist of continuous list of letters, numbers and underscore but cannot start with a number. Multiple variables can be assigned in one line by separating each variables and values with comma.


In [38]:
i,j,k = 23,45,17

In [39]:
i


Out[39]:
23

In [40]:
k


Out[40]:
17

Exercise 1.1: What is the profit before and after tax (45%) for a course:

  • Title: “How to use MATLAB like Pro”.
  • Participants: limited to 21 persons.
  • Fee: RM 15,000/person.
  • Duration: half a week.

$Solution$:

**********************************************************************


In [41]:
profit = 21*15000
profit


Out[41]:
315000

In [42]:
profit_after_tax = profit*45.0/100
profit_after_tax


Out[42]:
141750.0

**********************************************************************


1.6 Advanced Topic: Symbolic Computation

In symbolic computation, result of mathematical operation is represented exactly by unevaluated variables left in symbolic form. For instance, the mathematical operation of $\sqrt{8}$ will give result of a value of 2.83 but in symbolic computation, the result will be $2\sqrt{2}$. Python has symbolic mathematics (or sometime called computer algebra system or simply CAS) library called **sympy**. For a start, let try to symbolically evaluate $\sqrt{8}$:


In [43]:
import sympy as sp

sp.sqrt(8)


Out[43]:
2*sqrt(2)

the term import sympy as sp allows the calling of **sympy** functions simply by typing sp.{function name}. The expression can be operated upon, e.g. multiplication with 23.4 gives:


In [44]:
sp.sqrt(8)*23.4


Out[44]:
46.8*sqrt(2)

Operation on expression, e.g. $x$ **+** $y$ **+** $x$ that produce 2$x$ **+** $y$, can be performed by initially declaring $x$ and $y$ as symbolic representations:


In [45]:
x, y = sp.symbols('x y')
x + y + x


Out[45]:
2*x + y

The resulting expression can be assigned to variable and operated upon:


In [46]:
expr = x + y + y
2*expr


Out[46]:
2*x + 4*y

In [47]:
x*expr


Out[47]:
x*(x + 2*y)

The $sympy$ library allows users to works on derivatives, integrals, solve equations, matrices, and much more. Some of the examples are:

  • Solving the **$3x^2$ + $45x$ - $84$ = $0$** equation

In [48]:
sp.solve(3*x**2 + 45*x - 84, x)


Out[48]:
[-15/2 + sqrt(337)/2, -sqrt(337)/2 - 15/2]
  • Differentiation: $\frac{d}{dx}(cos(x)e^x)$

In [49]:
sp.diff(sp.cos(x)*sp.exp(x), x)


Out[49]:
-exp(x)*sin(x) + exp(x)*cos(x)
  • Integration: $\int{e^{x}sin(x)dx}$

In [50]:
sp.integrate(sp.exp(x)*sp.sin(x), x)


Out[50]:
exp(x)*sin(x)/2 - exp(x)*cos(x)/2
  • Computing $$\int_{-\infty}^\infty{\frac{1}{1 + x^{2}}}dx$$

In [51]:
sp.integrate(1/(1 + x**2), (x, -sp.oo, sp.oo))


Out[51]:
pi
  • Finding the determinant of the matrix $$\left[ \begin{array}{cc} 1 & 3 \\ 6 & 2\end{array} \right]$$

In [52]:
M = sp.Matrix(([1, 3], [6, 2]))

In [53]:
M


Out[53]:
Matrix([
[1, 3],
[6, 2]])

In [54]:
M.det()


Out[54]:
-16
  • Finding the product of $$\left[ \begin{array}{cc} 1 & 3 \\ 6 & 2\end{array} \right]\left[ \begin{array}{cc} 4 \\ 8\end{array} \right]$$

In [55]:
M1 = sp.Matrix(([1, 3], [6, 2]))
M2 = sp.Matrix(([4],[8]))
M1*M2


Out[55]:
Matrix([
[28],
[40]])

Further $sympy$ features can be found in http://docs.sympy.org/latest/tutorial/index.html